package comlookupd

import (
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"sync"
	"time"
)

var (
	MsgHandle map[string]func(string, map[string]interface{})
	ReqMap    sync.Map
	ComMap    sync.Map
	ConfigMap sync.Map
	FindMap   sync.Map
	RegOnce   sync.Once
)

func CommandMsgReceiver(sender string, resp typedef.CommandResponse) {
	MsgReceiver(sender, resp.ReqID, resp.Response)
}

func ComputeMsgReceiver(sender string, resp typedef.ComputeResponse) {
	MsgReceiver(sender, resp.ReqID, resp.Response)
}

func MsgReceiver(sender string, reqid string, data map[string]interface{}) {
	if v, ok := ReqMap.Load(reqid); ok {
		msgrecv := v.(typedef.MsgReceiver)
		if handle, exist := MsgHandle[msgrecv.Handle]; exist {
			handle(sender, data)
		}
		if !msgrecv.Mutex {
			ReqMap.Delete(reqid)
		}
	}
	pubsub.ClearReqMap(ReqMap)
}

func initMsgHandle() {
	MsgHandle = make(map[string]func(string, map[string]interface{}))
	MsgHandle["FindRegister"] = FindRegisterRecv
	MsgHandle["Health"] = HealthMsg

}

func FindRegisterRecv(sender string, data map[string]interface{}) {
	RegOnce.Do(func() {
		pubsub.CommandMsgPub(Config.Info.ID, sender, "Register", map[string]interface{}{"info": Config.Info})
	})
	resp := struct {
		Info typedef.ModuleInfo
	}{}
	if typedef.Decode(data, &resp) == nil && resp.Info.ID != "" {
		FindMap.Store(sender, typedef.ComInfo{
			Info:       resp.Info,
			LastUpdate: time.Now(),
		})
	}
}

func HealthMsg(sender string, data map[string]interface{}) {
	if v, ok := ComMap.Load(sender); ok {
		info := v.(typedef.ComInfo)
		info.LastUpdate = time.Now()
		ComMap.Store(sender, info)
	}
}
